package com.anpai.main;
// 模拟qq登录窗口

import com.anpai.entity.TitlesBean;
import com.anpai.entity.UserBean;

import com.anpai.entity.AdminBean;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.List;
import java.util.*;

public class LoginJFrame extends JFrame implements ActionListener {
    private JLabel userLa;
    private JLabel pwdLa;
    private JLabel verCodeLa;// 验证码
    static JTextField userTxt;
    private JPasswordField pwdTxt;
    private JTextField verCodeTxt;// 验证码
    private JButton sureBt;
    private JButton register;
    private JButton quitBt;
    private Mypanel mp;
    private static String xlsPath;
    public static String titlesPath;
    static HashMap<String, UserBean> userMap = new HashMap<>();
    static HashMap<String, AdminBean> adminMap = new HashMap<>();
    static HashMap<String, TitlesBean> titleMap = new HashMap<>();
    private JComboBox xlk;
    public static String path = System.getProperty("user.dir");



    public class Mypanel extends Panel {

        public void paint(Graphics g)
        {
            int height = 50;
            int width = 90;
            // 验证码框背景颜色
            g.setColor(Color.LIGHT_GRAY);
            // 填充验证码背景
            g.fillRect(0, 0, width, height);
            g.setColor(Color.BLACK);
            g.drawRect(0, 0, width-1, height-1);
            Random r = new Random();
            // 设置干扰点
            for(int i = 0;i<100;i++)
            {
                int x = r.nextInt(width)-1;
                int y = r.nextInt(height)-1;
                g.drawOval(x, y, 2, 2);
            }
            g.setFont(new Font("黑体",Font.BOLD,20));// 设置验证码字体以及大小
            g.setColor(Color.RED);// 设置验证码字体颜色
            // 生成随机验证码
            char[] tmp = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
            StringBuilder sb = new StringBuilder();
            for(int i = 0;i<4;i++)
            {
                int pos = r.nextInt(tmp.length);
                char c = tmp[pos];
                sb.append(c + " ");
            }
            g.drawString(sb.toString(), 10, 15);// 写入验证码
        }
    }

    // 构造方法
    public LoginJFrame()
    {
        this.setTitle("考试系统-用户登陆");
        Init();
    }
    public void Init()
    {
        // 用户文本
        userLa = new JLabel();
        userLa.setText("用户名：");
        userLa.setSize(60, 50);
        userLa.setLocation(100, 80);

        // 密码文本
        pwdLa = new JLabel();
        pwdLa.setText("密码：");
        pwdLa.setSize(50, 50);
        pwdLa.setLocation(100, 120);

        // 用户输入框
        userTxt = new JTextField();
        userTxt.setSize(100, 20);
        // this.setSize(width, height)
        userTxt.setLocation(170, 95);

        // 密码输入框
        pwdTxt = new JPasswordField();
        pwdTxt.setSize(100, 20);
        pwdTxt.setLocation(170, 135);

        // 确认按钮
        sureBt = new JButton("登录");
        sureBt.setSize(60, 25);
        sureBt.setLocation(80, 260);

        register = new JButton("注册");
        register.setSize(60,25);
        register.setLocation(170,260);

        // 退出按钮
        quitBt = new JButton("退出");
        quitBt.setSize(60, 25);
        quitBt.setLocation(260, 260);

        // 验证码文本
        verCodeLa = new JLabel();
        verCodeLa.setText("验证码：");
        verCodeLa.setSize(60, 50);
        verCodeLa.setLocation(100,165);

        // 验证码文本框
        verCodeTxt = new JTextField();
        verCodeTxt.setSize(100, 20);
        verCodeTxt.setLocation(170, 180);

        //  验证码
        mp = new Mypanel();
        mp.setSize(100, 30);
        mp.setLocation(280, 175);

        //  登录方式选择框
        xlk =new JComboBox();
        xlk.setSize(70, 20);
        xlk.setLocation(250, 220);
        xlk.addItem("用户");
        xlk.addItem("管理员");


        this.setLayout(null);
        setBounds(550,300,500, 400);
        this.add(userLa);
        this.add(pwdLa);
        this.add(userTxt);
        this.add(pwdTxt);
        this.add(sureBt);
        this.add(register);
        this.add(quitBt);
        this.add(verCodeLa);
        this.add(verCodeTxt);
        this.add(mp);
        this.add(xlk);
        sureBt.addActionListener(this);
        register.addActionListener(this);
        quitBt.addActionListener(this);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    // 具体事件的处理
    public void actionPerformed(ActionEvent e)
    {
        // 获取产生事件的事件源强制转换
        JButton bt = (JButton)e.getSource();
        // 获取按钮上显示的文本
        String str = bt.getText();
        if(str.equals("登录"))
        {
            if(!CheckIsNull())
            {
                if(xlk.getSelectedIndex() == 0){
                    xlsPath = path+"\\src\\main\\java\\com\\anpai\\data\\user.xls";
                }
                else {
                    xlsPath = path+"\\src\\main\\java\\com\\anpai\\data\\admin.xls";
                }
                // 获取用户所输入的用户名
                String user = userTxt.getText().trim();
                // 获取用户所输入的密码
                String pwd = pwdTxt.getText().trim();
                try {
                    // 获取所有用户
                    getUsers();
                    if(checkUserAndPwd(user,pwd,false)&&xlk.getSelectedIndex()==0)
                    {
                        // 隐藏当前登录窗口
                        this.setVisible(false);
                        // 验证成功创建一个主窗口
                        new CheckMessage.MyLayout();
                    }else if (checkUserAndPwd(user,pwd,true)&&xlk.getSelectedIndex()!=0){
                        this.setVisible(false);
                        new adminFrame();
                    }
                    else
                    {
                        // 如果错误则弹出一个显示框
                        JOptionPane pane = new JOptionPane("用户或密码错误");
                        JDialog dialog  = pane.createDialog(this,"警告");
                        dialog.show();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }else if (str.equals("注册")){

            new registerFrame();
        }
        else
        {
            // 调用系统类中的一个正常退出
            System.exit(0);
        }
    }
    private boolean CheckIsNull()
    {
        boolean flag = false;
        if(userTxt.getText().trim().equals(" "))
        {
            flag = true;
        }
        else
        {
            if(pwdTxt.getText().trim().equals(" "))
            {
                flag = true;
            }
        }
        return flag;
    }

    public static Workbook getWorkbook(String filePath, InputStream in){
        Workbook workbook = null;
        try {
                workbook = new HSSFWorkbook(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    // 获取题库
    public static void getTitles() throws FileNotFoundException {
        Workbook wb = getWorkbook(titlesPath,new FileInputStream(titlesPath));
        Sheet sheet = wb.getSheetAt(0);
        int totalRows = sheet.getPhysicalNumberOfRows();
        List<TitlesBean> list = new ArrayList<TitlesBean>();
        for(int i = 1; i < totalRows; i++){
            Row row = sheet.getRow(i);
            String[] strings = new String[10];
            // System.out.println(totalColumn);
            for(int j = 0; j < 9; j++){
                Cell cell = row.getCell(j);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                strings[j]=cell.getStringCellValue();
            }
            TitlesBean titlesList = new TitlesBean(strings[0],strings[1],strings[2],strings[3],strings[4],strings[5],strings[6],strings[7],strings[8]);
            list.add(titlesList);
            titleMap.put(strings[0],titlesList);

        }
    }

    // 获取所有用户
    private static void getUsers() throws FileNotFoundException {
        Workbook wb = getWorkbook(xlsPath,new FileInputStream(xlsPath));
        // wb 指向了具体excel文件的对象
        Sheet sheet = wb.getSheetAt(0); // 获取对应excel文件的第一个sheet
        Row sheetRow = sheet.getRow(sheet.getFirstRowNum());
        short lastCellNum = sheetRow.getLastCellNum();
        // getPhysicalNumberOfRows ： 获取当前sheet中的有效数据行数（甚至是设置了样式，POI也认为是一个有效的数据行）
        int totalRows = sheet.getPhysicalNumberOfRows();
        List<UserBean> list = new ArrayList<UserBean>();
        List<AdminBean> adminlist = new ArrayList<AdminBean>();
        for(int i = 1; i < totalRows; i++){
            Row row = sheet.getRow(i);
            String[] strings = new String[lastCellNum];
            // System.out.println(totalColumn);
            for(int j = 0; j < lastCellNum; j++){
                Cell cell = row.getCell(j);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                strings[j]=cell.getStringCellValue();
            }
            if(lastCellNum==8) {
                UserBean userList = new UserBean(strings[0], strings[1], strings[2], strings[3], strings[4], strings[5], strings[6], strings[7]);
                list.add(userList);
                userMap.put(strings[1],userList);
            }else {
                AdminBean admin = new AdminBean(strings[0], strings[1], strings[2], strings[3]);
                adminlist.add(admin);
                adminMap.put(strings[1],admin);
            }

        }
    }

    // 判断用户帐号和密码
    private static boolean checkUserAndPwd(String user, String pwd,boolean isAdmin) throws Exception{
        boolean result = false;
        UserBean value;
        AdminBean admin;
        String key;
        Iterator it = userMap.keySet().iterator();
        Iterator iterator = adminMap.keySet().iterator();
        if (isAdmin){
            while (iterator.hasNext()){
                key= String.valueOf(iterator.next());
                admin = adminMap.get(key);
                if (user.equals(key)){
                    if (admin.getAdminPwd().equals(pwd)){
                        result=true;
                        break;
                    }
                }
            }
        }
        else {
        while (it.hasNext()) {
            key = (String) it.next();
            value = userMap.get(key);
            if(user.equals(key)){
                if(value.getPassword().equals(pwd)){
                    result = true;
                    break;
                }
            }
          }
        }
        return result;
    }



}




